#include "client.h"

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int socketFd;
    //初始化一个socket，有一个缓冲区
    socketFd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("client : socketFd=%d\n",socketFd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_port=htons(atoi(argv[2]));
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    int ret;
    ret=connect(socketFd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    printf("client : connected\n");
    
    char buf[1000] = {0};
    //接收文件名
    int dataLen = 0;
    recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);//length of filename
    recv(socketFd,buf,dataLen,MSG_WAITALL);//filename

    //接收 文件大小
    off_t fileLen = 0;
    recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);
    recv(socketFd,&fileLen,dataLen,MSG_WAITALL);
    //printf("recv fileLen: %ld\n",fileLen);
    //创建新文件准备接收
    int fd;
    int i = 1;
    int buflen = strlen(buf);
    int tmp = buflen;
    // 这里实现如果有重名的文件，则在新建文件名后边加递增的数字，直到没有重名
    while(-1 == (fd = open(buf,O_WRONLY|O_CREAT|O_EXCL,0666)))
    {
        tmp = buflen;
        while(buf[tmp])
        {
            buf[tmp++] = 0;
        }
        sprintf(buf,"%s%d",buf,i++);
    }
    
    
    //接收文件内容
    printf("Receiving file : name %s size : %ld M\n",buf,fileLen/(1024*1024));
    off_t curLen = 0;
    while(1)
    {
        //得到train的数据长度
        recvCycle(socketFd,&dataLen,sizeof(int));
        //recv(socketFd,&dataLen,sizeof(int),MSG_WAITALL);
        curLen+=dataLen;
        if(dataLen)
        {
            loadingBar(curLen,fileLen);//每次接收数据之后更新进度条
            recvCycle(socketFd,buf,dataLen);
            // recv(socketFd,buf,dataLen,MSG_WAITALL);
            write(fd,buf,dataLen);
            
        }else{
            printf("\n");//打印完loadingBar之后打一个换行
            break;
        }
    }
    

    close(socketFd);
    return 0;
}
